﻿using Microsoft.Practices.Prism.Regions;
using System.Collections.Specialized;
using System.Windows;

namespace Ags.MonsterTools
{
    public class WindowRegionAdapter : RegionAdapterBase<Window>
    {
        public WindowRegionAdapter(IRegionBehaviorFactory factory)
            : base(factory)
        {
        }
        protected override void Adapt(IRegion region, Window regionTarget)
        {
            region.Views.CollectionChanged += (s, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (FrameworkElement element in e.NewItems)
                    {
                        var childWindow = element as Window;
                        if (childWindow != null)
                        {
                            childWindow.Owner = regionTarget;
                            childWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                            childWindow.Show();
                        }
                    }
                }
                else if (e.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (FrameworkElement element in e.OldItems)
                    {
                        var childWindow = element as Window;
                        if (childWindow != null)
                            childWindow.Close();
                    }
                }
            };
        }

        protected override IRegion CreateRegion()
        {
            return new AllActiveRegion();
        }
    }
}
